package com.googlecode.yoohoo.xmppcore.protocol.stream;

import java.util.List;

import com.googlecode.yoohoo.xmppcore.protocol.parsing.Attribute;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParser;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.IXmppParserFactory;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.ProtocolKey;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.XmppParserAdapter;
import com.googlecode.yoohoo.xmppcore.protocol.stanza.error.BadRequest;
import com.googlecode.yoohoo.xmppcore.utils.ErrorUtils;

public class SessionParserFactory implements IXmppParserFactory<Session> {
	
	@Override
	public IXmppParser<Session> createParser() {
		return new SessionParser();
	}

	@Override
	public ProtocolKey getProtocolKey() {
		return Session.PROTOCOL_KEY;
	}
	
	private class SessionParser extends XmppParserAdapter<Session> {
		private static final String PATH_SESSION = "session";
		private Session session;

		@Override
		public Session getObject() {
			return session;
		}
		
		@Override
		public void processAttributes(String path, List<Attribute> attributes) {
			if (PATH_SESSION.equals(path)) {
				if (attributes.size() > 0) {
					throw ErrorUtils.createProtocolException("Invalid attribute for 'session' element.",
							new BadRequest());
				}
				
				session = new Session();
			} else {
				throw ErrorUtils.createProtocolException(String.format(
					"Invalid parsing path '%s'.", path), new BadRequest());
			}
		}
		
		@Override
		public void processText(String path, String text) {
			if (text != null) {
				throw ErrorUtils.createProtocolException("'session' must be an empty element.",
						new BadRequest());
			}
		}
	}
}
